package web.pre;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.naming.SizeLimitExceededException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadBase.FileSizeLimitExceededException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.alibaba.fastjson.JSON;

import entity.Product;
import entity.ProductCategory;
import service.ProductCategoryService;
import service.ProductService;
import utils.PageUtils;
import utils.ReturnResult;

public class AdminProductServlet extends HttpServlet{
	public ProductService  productService=new ProductService();
	public ProductCategoryService productCategoryService=new ProductCategoryService();
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		String action = request.getParameter("action");
		if (action != null) {
			switch (action) {
			case "index":
				index(request,response);
				break;
			case "toAddProduct":
				toAddProduct(request,response);
				break;
			case "addProduct":
				addProduct(request,response);
				break;
			case "toUpdateProduct":
				toUpdateProduct(request,response);
				break;
			case "updateProduct":
				updateProduct(request,response);
				break;
			case "deleteProduct":
				deleteProduct(request,response);
				break;
			default:
				response.sendRedirect("404.jsp");
				break;
			}
		} else {
			response.sendRedirect("404.jsp");
		}
	}
	private void deleteProduct(HttpServletRequest request, HttpServletResponse response)throws IOException {
		// TODO Auto-generated method stub
		PrintWriter out = response.getWriter();
		ReturnResult returnResult = new ReturnResult(0,"删除商品失败");
		int id = Integer.parseInt(request.getParameter("id"));
		int result2 =productService.deteleProduct(id);
		if (result2 > 0) {
        	returnResult.setStatus(1);
        	returnResult.setMessage("删除商品成功");
		}
	
	    String jsonStr = JSON.toJSONString(returnResult);
	
    	out.print(jsonStr);
	
     	out.flush();
	     out.close();
	}
	private void updateProduct(HttpServletRequest request, HttpServletResponse response) throws IOException {
		PrintWriter out = response.getWriter();
		ReturnResult returnResult = new ReturnResult(0,"修改商品失败");
		//用来装普通字段
		Map<String, String> params = new HashMap<String, String>();
		//定义支持的文件
		List<String> fileType = Arrays.asList("jpg","gif","png");
		
		String uploadFilePath = request.getSession().getServletContext().getRealPath("files/"); //服务器保存 文件上传 的位置（路径）
		
		FileItemFactory factory = new DiskFileItemFactory();
		ServletFileUpload upload = new ServletFileUpload(factory);
		
		// 单位是 byte ，1kb = 1024byte
		upload.setSizeMax(200*1024); //限制总的文件大小
		
		upload.setFileSizeMax(10*1024); //限制单个文件大小
		String fileName = null;
		try {
			List<FileItem> items = upload.parseRequest(request);
			
			for (FileItem item : items) {
				
				if (item.isFormField()) { //判断item是一个普通表单元素
					params.put(item.getFieldName(), item.getString("utf-8"));
				} else { //不是普通元素，那就是文件元素
					// item.getName() 用户选择的文件路径
					if (item.getName() != null && !item.getName().equals("")) { //非空判断，判断用户有没有选择文件
						//拿到文件名
						fileName = item.getName().substring(item.getName().lastIndexOf("."));
						//对文件名进行更改，以防重名被覆盖
						fileName = UUID.randomUUID() + fileName ;
						File targetFile = new File(uploadFilePath,fileName); //目标文件
						
						// 获取文件的后缀 aaa.jpg 
						String ext = fileName.substring(fileName.indexOf(".")+1);
						
						if (!fileType.contains(ext)) { //是否支持格式
							returnResult.setMessage("文件上传失败，格式不正确，只支持jpg/png/gif");
						} else {
							item.write(targetFile); //上传
						}
						
						
					}
				}
				
			}
			
			String id=params.get("id");
			String name=params.get("name");
			String description=params.get("description");
			String price=params.get("price");
			String stock=params.get("stock");
			String categoryLevel1Id=params.get("categoryLevel1Id");
			String categoryLevel2Id=params.get("categoryLevel2Id");
			String categoryLevel3Id=params.get("categoryLevel3Id");
			
			Product product=new Product();
			product.setName(name);
			product.setDescription(description);
			product.setPrice(Float.valueOf(price));
			product.setStock(Integer.parseInt(stock));
			product.setCategoryLeve1(Integer.parseInt(categoryLevel1Id));
			product.setCategoryLeve2(Integer.parseInt(categoryLevel2Id));
			product.setCategoryLeve3(Integer.parseInt(categoryLevel3Id));
			product.setId(Integer.parseInt(id));
			
			//设置文件，如果没有更改文件
			if (fileName==null || fileName=="") {
				Product oldProduct=productService.getProductById(Integer.valueOf(id));
				product.setFileName(oldProduct.getFileName());
			} else {
				product.setFileName(fileName);
			}
			
			int result = productService.update(product);
			
			if (result > 0) {
	        	returnResult.setStatus(1);
	        	returnResult.setMessage("修改商品成功");
			}
			
		} catch (FileSizeLimitExceededException e) {
			returnResult.setMessage("单个文件太大，最大限制为："+(upload.getFileSizeMax()/1024)+"kb");
		} catch (SizeLimitExceededException e) {
			returnResult.setMessage("总的文件太大，最大限制为："+(upload.getSizeMax()/1024)+"kb");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		String jsonStr = JSON.toJSONString(returnResult);
		
		out.print(jsonStr);
		
		out.flush();
		out.close();
		
	}

	private void toUpdateProduct(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String id=request.getParameter("id");
		Product product=productService.getProductById(Integer.valueOf(id));
		request.setAttribute("product", product);
		
		//拿一级分类
		List<ProductCategory> productCategoryList1=productCategoryService.findListByType(1);
		//拿二级分类
		List<ProductCategory> productCategoryList2=productCategoryService.findAllByParentId(product.getCategoryLeve1());
		//拿三级分类
		List<ProductCategory> productCategoryList3=productCategoryService.findAllByParentId(product.getCategoryLeve2());
		
		request.setAttribute("productCategoryList1", productCategoryList1);
		request.setAttribute("productCategoryList2", productCategoryList2);
		request.setAttribute("productCategoryList3", productCategoryList3);
		
		request.getRequestDispatcher("backend/product/toAddProduct.jsp").forward(request, response);
	}

	private void addProduct(HttpServletRequest request, HttpServletResponse response) throws IOException {
		PrintWriter out = response.getWriter();
		ReturnResult returnResult = new ReturnResult(0,"新增商品失败");
		//用来装普通字段
		Map<String, String> params = new HashMap<String, String>();
		//定义支持的文件
		List<String> fileType = Arrays.asList("jpg","gif","png");
		
		String uploadFilePath = request.getSession().getServletContext().getRealPath("files/"); //服务器保存 文件上传 的位置（路径）
		
		FileItemFactory factory = new DiskFileItemFactory();
		ServletFileUpload upload = new ServletFileUpload(factory);
		
		// 单位是 byte ，1kb = 1024byte
		upload.setSizeMax(200*1024); //限制总的文件大小
		
		upload.setFileSizeMax(100*1024); //限制单个文件大小
		String fileName = null;
		try {
			List<FileItem> items = upload.parseRequest(request);
			
			for (FileItem item : items) {
				
				if (item.isFormField()) { //判断item是一个普通表单元素
					params.put(item.getFieldName(), item.getString("utf-8"));
				} else { //不是普通元素，那就是文件元素
					// item.getName() 用户选择的文件路径
					if (item.getName() != null && !item.getName().equals("")) { //非空判断，判断用户有没有选择文件
						//拿到文件名
						fileName = item.getName().substring(item.getName().lastIndexOf("."));
						//对文件名进行更改，以防重名被覆盖
						fileName = UUID.randomUUID() + fileName ;
						File targetFile = new File(uploadFilePath,fileName); //目标文件
						
						// 获取文件的后缀 aaa.jpg 
						String ext = fileName.substring(fileName.indexOf(".")+1);
						
						if (!fileType.contains(ext)) { //是否支持格式
							returnResult.setMessage("文件上传失败，格式不正确，只支持jpg/png/gif");
						} else {
							item.write(targetFile); //上传
						}
						
						
					}
				}
				
			}
			
			String id=params.get("id");
			String name=params.get("name");
			String description=params.get("description");
			String price=params.get("price");
			String stock=params.get("stock");
			String categoryLevel1Id=params.get("categoryLevel1Id");
			String categoryLevel2Id=params.get("categoryLevel2Id");
			String categoryLevel3Id=params.get("categoryLevel3Id");
			
			Product product=new Product();
			product.setName(name);
			product.setDescription(description);
			product.setPrice(Float.valueOf(price));
			product.setStock(Integer.parseInt(stock));
			product.setCategoryLeve1(Integer.parseInt(categoryLevel1Id));
			product.setCategoryLeve2(Integer.parseInt(categoryLevel2Id));
			product.setCategoryLeve3(Integer.parseInt(categoryLevel3Id));
//			product.setId(Integer.parseInt(id));
			
			product.setFileName(fileName);
			
			int result = productService.add(product);
			
			if (result > 0) {
	        	returnResult.setStatus(1);
	        	returnResult.setMessage("新增商品成功");
			}
			
		} catch (FileSizeLimitExceededException e) {
			returnResult.setMessage("单个文件太大，最大限制为："+(upload.getFileSizeMax()/1024)+"kb");
		} catch (SizeLimitExceededException e) {
			returnResult.setMessage("总的文件太大，最大限制为："+(upload.getSizeMax()/1024)+"kb");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		String jsonStr = JSON.toJSONString(returnResult);
		
		out.print(jsonStr);
		
		out.flush();
		out.close();
		
	}

	private void toAddProduct(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		List<ProductCategory> productCategoryList1=productCategoryService.findListByType(1);
		request.setAttribute("productCategoryList1", productCategoryList1);
		request.getRequestDispatcher("backend/product/toAddProduct.jsp").forward(request, response);
	}
	/**
	 * 跳转到商品列表页面，要分页
	 * @param request
	 * @param response
	 * @throws IOException 
	 * @throws ServletException 
	 */
	private void index(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		int currPageNo = 1;
		int pageSize = 6;
		
		String paramCurrPageNo = request.getParameter("currPage");
		if (paramCurrPageNo != null && !"".equals(paramCurrPageNo)) {
			currPageNo = Integer.parseInt(paramCurrPageNo);
		}
		
		PageUtils<Product> pageUtil = productService.findAllProducts(currPageNo,pageSize);
		
		pageUtil.setCurrPage(currPageNo);
		//listProduct
		request.setAttribute("pageUtil", pageUtil);
		request.getRequestDispatcher("backend/product/productList.jsp").forward(request, response);
		
	}

	
	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		this.doGet(request, response);
	}
}
